package de.homelabs.xml.menu.parser;

import javax.xml.bind.JAXBContext;
import javax.xml.bind.Unmarshaller;

import org.apache.log4j.Logger;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.core.io.Resource;
import org.springframework.stereotype.Service;

import spiffy.log4j.LoggerHelper;
import de.homelabs.exception.HException;
import de.homelabs.xml.menu.Menu;
import de.homelabs.xml.menu.MenuActionEntry;
import de.homelabs.xml.menu.RootMenuEntry;

@Service("hJaxbParser")
public class HJaxbParser implements IMenuParser, ApplicationContextAware{

	//logger
	public static final Logger logger = LoggerHelper.getLogger();
	
	private ApplicationContext context;
	
	public Menu parseMenuXml(String fileName) throws HException{
		try {
			//Menu Container 
			Menu menuContainer = new Menu();
			//file resource
			Resource[] resources = context.getResources("classpath*:"+fileName);
			//Resource resource = context.getResource("classpath:core-menu.xml");
			
			//jax unmarshaller
			JAXBContext jc = JAXBContext.newInstance("de.homelabs.xml.menu");
		    Unmarshaller unmarshaller = jc.createUnmarshaller();
		    
		    for (Resource resource : resources){
		    	logger.debug("Resource found: "+resource.getFilename());
			    Menu menu = (Menu) unmarshaller.unmarshal(resource.getFile());
		
			    //root menu output
			    for (RootMenuEntry rm : menu.getRootMenuEntry()){
			    	logger.debug("Root Menu: "+rm.getLableKey()+","+rm.getActionKey());
			    	menuContainer.getRootMenuEntry().add(rm);
			    }
			    
			    //menu action output
			    for (MenuActionEntry entry : menu.getMenuActionEntry()){
			    	logger.debug("MenuAction: "+entry.getLableKey()+","+entry.getActionKey()+","+entry.getParent());
			    	menuContainer.getMenuActionEntry().add(entry);
			    }
		    }
		    
		    //return container
		    return menuContainer;
		} catch (Exception e){
			throw new HException("Error parsing menu config file(s): "+fileName+"! Exception detail:"+e);
		}
	}

	@Override
	public void setApplicationContext(ApplicationContext applicationContext)
			throws BeansException {
		this.context = applicationContext;	
	}
}
